package com.zwf.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zwf.constant.MessageConstant;
import com.zwf.context.BaseContext;
import com.zwf.dto.*;
import com.zwf.entity.*;
import com.zwf.exception.AddressBookBusinessException;
import com.zwf.exception.OrderBusinessException;
import com.zwf.exception.ShoppingCartBusinessException;
import com.zwf.mapper.*;
import com.zwf.result.PageResult;
import com.zwf.service.OrderService;
import com.zwf.utils.WeChatPayUtil;
import com.zwf.vo.OrderPaymentVO;
import com.zwf.vo.OrderStatisticsVO;
import com.zwf.vo.OrderSubmitVO;
import com.zwf.vo.OrderVO;
import com.zwf.websocket.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author zwf
 * @date 2024/2/11 13:45
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    AddressBookMapper addressBookMapper;

    @Autowired
    ShoppingCartMapper shoppingCartMapper;

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    OrderDetailMapper orderDetailMapper;

    @Autowired
    UserMapper userMapper;

    @Autowired
    WeChatPayUtil weChatPayUtil;

    @Autowired
    WebSocketServer webSocketServer;

    /**
     * 用户下单
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    @Transactional
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {

        //处理各种业务异常（地址簿为空，购物车数据为空）
        //地址簿为空
        AddressBook addressBook=new AddressBook();
        addressBook.setId(ordersSubmitDTO.getAddressBookId());
        List<AddressBook> list = addressBookMapper.list(addressBook);
        AddressBook ab=list.get(0);
        if(ab==null){
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        //购物车数据为空
        ShoppingCart shoppingCart=new ShoppingCart();
        shoppingCart.setUserId(BaseContext.getCurrentId());
        List<ShoppingCart> cartList = shoppingCartMapper.list(shoppingCart);
        if(cartList==null||cartList.size()==0){
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //向订单表插入一条数据
        Orders orders=new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO,orders);
        orders.setOrderTime(LocalDateTime.now());
        orders.setUserId(BaseContext.getCurrentId());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setNumber(String.valueOf(System.currentTimeMillis())+BaseContext.getCurrentId());  //生成一个唯一订单号
        orders.setPhone(ab.getPhone());
        orders.setConsignee(ab.getConsignee());
        orders.setAddress(ab.getDistrictName()+ab.getDetail());
        orderMapper.add(orders);

        //向订单明细表插入n条数据
        List<OrderDetail> orderDetails =new ArrayList<>();
        cartList.forEach(cart->{
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orders.getId());
            BeanUtils.copyProperties(cart,orderDetail);
            orderDetails.add(orderDetail);
        });
        orderDetailMapper.addBatch(orderDetails);

        //清空当前用户的购物车数据
        ShoppingCart shoppingCart1=new ShoppingCart();
        shoppingCart1.setUserId(BaseContext.getCurrentId());
        shoppingCartMapper.delete(shoppingCart1);

        //封装VO返回结果
        OrderSubmitVO orderSubmitVO=new OrderSubmitVO();
        orderSubmitVO.setId(orders.getId());
        orderSubmitVO.setOrderTime(orders.getOrderTime());
        orderSubmitVO.setOrderAmount(orders.getAmount());
        orderSubmitVO.setOrderNumber(orders.getNumber());

        return orderSubmitVO;
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

//        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "校园点餐系统订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );

        //生成空JSON，跳过微信支付流程
        JSONObject jsonObject=new JSONObject();

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);


        //给管理端推送来单提醒
        Map map=new HashMap();
        map.put("type",1);  //1：来单提醒  2：用户催单
        map.put("orderId",ordersDB.getId());  //获取订单id
        map.put("content","订单号："+outTradeNo);  //订单号
        String jsonString = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(jsonString);

    }

    /**
     * 查询订单详情
     * @param id
     * @return
     */
    @Override
    public OrderVO orderDetail(Long id) {
        OrderDetail orderDetail=new OrderDetail();
        orderDetail.setOrderId(id);
        List<OrderDetail> orderDetailList=orderDetailMapper.list(orderDetail);

        Orders orders=orderMapper.getById(id);

        OrderVO orderVO=new OrderVO();
        BeanUtils.copyProperties(orders,orderVO); //即使orderVO中没有orders中的属性，orderVO转为JSON字符串后照样能查看order拷贝过来的属性
        orderVO.setOrderDetailList(orderDetailList);
        return orderVO;
    }

    /**
     * 历史订单查询
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(OrdersPageQueryDTO ordersPageQueryDTO) {
        //分页查询订单表，用Order接收
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        Page<Orders> page=orderMapper.pageQuery(ordersPageQueryDTO);

        //将Order拷贝给OrderVO
        List<OrderVO> orderVOList=new ArrayList<>();
        if(page.getResult()!=null&&page.getResult().size()>0){
            page.getResult().forEach(orders -> {
                OrderVO orderVO=new OrderVO();
                BeanUtils.copyProperties(orders,orderVO);

                //查询订单详情
                OrderDetail orderDetail=new OrderDetail();
                orderDetail.setOrderId(orders.getId());
                List<OrderDetail> orderDetailList=orderDetailMapper.list(orderDetail);
                orderVO.setOrderDetailList(orderDetailList);

                orderVOList.add(orderVO);
            });
        }

        //封装PageResult对象
        PageResult pageResult=new PageResult();
        pageResult.setTotal(page.getTotal());
        pageResult.setRecords(orderVOList);
        return pageResult;
    }

    /**
     * 取消订单
     * @param id
     */
    @Override
    public void cancelOrder(Long id) {

        Orders orders = orderMapper.getById(id);

        //待支付和待接单状态下，用户可直接取消订单，否则需电话沟通商家
        if(orders.getStatus()>2){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        //TODO 电话联系

        //如果在待接单状态下取消订单，需要给用户退款
        if(orders.getStatus().equals(Orders.TO_BE_CONFIRMED)){
            orders.setPayStatus(Orders.REFUND);
        }

        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason("用户取消");
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    /**
     * 再来一单
     * @param id
     */
    @Override
    public List<ShoppingCartDTO> repetition(Long id) {
        OrderDetail orderDetail=new OrderDetail();
        orderDetail.setOrderId(id);

        List<ShoppingCartDTO> shoppingCartDTOS=new ArrayList<>();

        //将当前订单的明细封装成List<ShoppingCartDTO>
        List<OrderDetail> detailList = orderDetailMapper.list(orderDetail);
        detailList.forEach(single->{
            for (int i = 0; i < single.getNumber(); i++) {
                ShoppingCartDTO shoppingCartDTO=new ShoppingCartDTO();
                BeanUtils.copyProperties(single,shoppingCartDTO);
                shoppingCartDTOS.add(shoppingCartDTO);
            }
        });
        return shoppingCartDTOS;
    }

    /**
     * 订单搜索
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult list(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        Page<Orders> orders = orderMapper.pageQuery(ordersPageQueryDTO);
        PageResult pageResult=new PageResult();
        pageResult.setTotal(orders.getTotal());
        pageResult.setRecords(orderVOS(orders));

        return pageResult;
    }

    //将Orders对象信息拷贝到OrderVO对象中
    private List<OrderVO> orderVOS(Page<Orders> orders){

        List<OrderVO> orderVOS=new ArrayList<>();

        List<Orders> result = orders.getResult();
        if(!CollectionUtils.isEmpty(result)){
            result.forEach(single->{
                OrderVO orderVO = new OrderVO();
                String orderDishes = orderDishes(single);
                orderVO.setOrderDishes(orderDishes);
                BeanUtils.copyProperties(single,orderVO);
                orderVOS.add(orderVO);
            });
        }
        return orderVOS;
    }

    //部分订单状态，需要额外返回订单菜品信息。将菜品信息封装到OrderVO的orderDishes中
    private String orderDishes(Orders orders){
        OrderDetail orderDetail=new OrderDetail();
        orderDetail.setOrderId(orders.getId());
        List<OrderDetail> detailList = orderDetailMapper.list(orderDetail);
        List<String> strings = detailList.stream().map(x -> {
            String orderDish = x.getName() + "*" + x.getNumber() + ";";
            return orderDish;
        }).collect(Collectors.toList());
        String join = String.join("", strings);
        return join;
    }

    /**
     * 查询订单详情
     * @param id
     * @return
     */
    @Override
    public OrderVO details(Long id) {

        OrderVO orderVO = new OrderVO();

        Orders orders = orderMapper.getById(id);
        BeanUtils.copyProperties(orders,orderVO);

        OrderDetail orderDetail=new OrderDetail();
        orderDetail.setOrderId(id);
        List<OrderDetail> detailList = orderDetailMapper.list(orderDetail);
        orderVO.setOrderDetailList(detailList);
        return orderVO;
    }

    /**
     * 各个状态的订单数量统计
     * @return
     */
    @Override
    public OrderStatisticsVO count() {
        OrderStatisticsVO orderStatisticsVO=new OrderStatisticsVO();
        Orders orders=new Orders();

        //待接单数
        orders.setStatus(Orders.REFUND);
        Integer toBeC =orderMapper.count(orders);

        //待派送数
        orders.setStatus(Orders.CONFIRMED);
        Integer conf=orderMapper.count(orders);

        //派送中数
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        Integer deli=orderMapper.count(orders);

        orderStatisticsVO.setToBeConfirmed(toBeC);
        orderStatisticsVO.setConfirmed(conf);
        orderStatisticsVO.setDeliveryInProgress(deli);
        return orderStatisticsVO;
    }

    /**
     * 接单
     * @param confirmDTO
     */
    @Override
    public void confirm(OrdersConfirmDTO confirmDTO) {
        Orders orders=new OrderVO();
        orders.setId(confirmDTO.getId());
        orders.setStatus(Orders.CONFIRMED);
        orderMapper.update(orders);
    }

    /**
     * 拒单
     * @param ordersRejectionDTO
     */
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        Orders orders=Orders.builder()
                .id(ordersRejectionDTO.getId())
                .status(Orders.CANCELLED)
                .cancelReason(ordersRejectionDTO.getRejectionReason())
                .rejectionReason(ordersRejectionDTO.getRejectionReason())
                .cancelTime(LocalDateTime.now())
                .build();
        //如果用户已支付，需要为其退款
        if(orderMapper.getById(ordersRejectionDTO.getId()).getPayStatus()==Orders.PAID){
            orders.setPayStatus(Orders.REFUND);
        }
        orderMapper.update(orders);
    }

    /**
     * 派送订单
     * @param id
     */
    @Override
    public void delivery(Long id) {
        Orders orders=Orders.builder()
                .id(id)
                .status(Orders.DELIVERY_IN_PROGRESS)
                .build();
        orderMapper.update(orders);
    }

    /**
     * 完成订单
     * @param id
     */
    @Override
    public void complete(Long id) {
        Orders orders=Orders.builder()
                .id(id)
                .status(Orders.COMPLETED)
                .deliveryTime(LocalDateTime.now())
                .build();
        orderMapper.update(orders);
    }

    /**
     * 取消订单
     * @param ordersCancelDTO
     */
    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        Orders orders=Orders.builder()
                .id(ordersCancelDTO.getId())
                .status(Orders.CANCELLED)
                .cancelReason(ordersCancelDTO.getCancelReason())
                .cancelTime(LocalDateTime.now())
                .build();
        orderMapper.update(orders);
    }

    /**
     * 来单提醒
     * @param id
     */
    @Override
    public void reminder(Long id) {
        Orders orders = orderMapper.getById(id);
        Map map=new HashMap();
        map.put("type",2);
        map.put("orderId",id);
        map.put("content","订单号："+orders.getNumber());
        String jsonString = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(jsonString);
    }
}
